<?php
define('TEMP_FILE', './Uploads/image');
/**
 * nmp版 - 新后台多账号运营
 * Class IndMediaAction
 * @author lilei<LL_strive@163.com> 2017-07-04
 */
class IndMediaAction extends Action {

    /**
     * 类初始化函数
     */
    public function _initialize()
    {

    }

    /**
     * 获得运营的自媒体账号列表
     *
     * @param null $name    按名称筛选
     * @param null $type    按类型筛选:1-wx/2-wb/3-tth
     * @param int  $start
     * @param int  $limit
     */
    public function getIndMediaList($name = null, $type = null, $start = 0, $limit = 10, $gg_cid = 0, $needReturn = FALSE, $isFromStatistics = '')
    {
        /** 1. 判断是否登录 */
        $this->retVal = Session::init();
        if (!$this->retVal && !$needReturn) {
            Output::instance()->resultCode(code_access_denied);
            exit;
        }

        // 注意这地方要替换正式的url
        /** 设置默认数据, 依次是wx/wb/tth */
        $picUrls = [    // 默认封面图url
            'http://oss.mboxone.com/20170711/image/96/1499763222882465.jpeg',
            'http://oss.mboxone.com/20170711/image/96/1499763312584837.jpeg',
            'http://oss.mboxone.com/20170711/image/96/1499763344762873.jpeg'
        ];
        $iconUrls = [   // 默认icon的url
            'http://oss.mboxone.com/20170711/image/96/1499763222882465.jpeg',
            'http://oss.mboxone.com/20170711/image/96/1499763312584837.jpeg',
            'http://oss.mboxone.com/20170711/image/96/1499763344762873.jpeg'
        ];
        $defaultMainName = '默认主账号';
        $nick_names = [
            '新建微信账号', '新建微博账号', '新建头条账号'
        ];

        /** 2. 数据表模型 */
        $userId     = Session::$user['id'];
        $customerId = ($gg_cid == 0) ? Session::$user['customerId'] : $gg_cid;
        Session::switchCustomer(0);
        $IndMediaInfo_model   = M('ind_media_info');
        $IndMediaEdit_model   = M('ind_media_edit');
        $CustomerUser_model   = M('customer_user');
        $GroupUser_model      = M('group_user');
        Session::switchCustomer($customerId);

        /** 3. 筛选条件 */
        $where_info = [];
        $where_info['deleted'] = 0;
        /** 3.1 判断登录者身份 */
        /** 这里假设平台超级管理员是不会到这里的, 到这里, 走的是else */
        if (Session::isBusiness() || ($gg_cid != 0) || $isFromStatistics == 1) {    // 如果是运营管理员或者是来自数据分析, 则直接查询cid
            $where_info['imi.cid']   = array('eq', $customerId);
        } else {    // 如果是普通运营人员, 则通过ind_media_edit过滤查询这个用户管理的这些账号

            // 考虑组级的关系: 组长可以看到该组所有组员所运营的账号
            $where_group = [
                'userId'    => $userId,
                'leader'    => 1
            ];
            // 这里的infoId是组id, 这里获取的是以这个用户为组长的组
            $infoIds = $GroupUser_model->where($where_group)->getField('infoId', true);
            if (empty($infoIds)) {  // 如果以他为组长的组为空, 则组员只有自己
                $userIds = [ $userId ];   // 为了与下面统一, 这里也写成一个数组

            } else {
                // 获得以该用户为组长的所有组的所有组员, 这里必然会有用户id重复, 所以在下面做了去重
                $userIds = $GroupUser_model->where(['infoId' => array('in', $infoIds)])->getField('userId', true);
                $userIds = array_keys(array_flip($userIds));    // 数组去重
            }

            // 根据所有组员(运营人员)的ids, 去查这些人名下的所有账号mediaIds
            $where_edit = ['cid' => $customerId, 'userId' => array('in', $userIds)];
            $mediaIds = $IndMediaEdit_model->where($where_edit)->getField('mediaId', true);
            $mediaIds = isset($mediaIds) ? $mediaIds : [];
            $mediaIds = array_keys(array_flip($mediaIds));    // 数组去重

            // 最后设置过滤筛选条件, 选出这些账号
            $where_info['imi.id']   = array('in', $mediaIds);   // 这个普通运营人员名下的账号信息
        }

        /** 3.2 其他筛选过滤条件 */
        $where_info['imi.type']  = array('eq', $type);
        // 过滤除平台默认账号外未授权的空账号
        $map_info['profile.grantStatus'] = array('EQ', 1);
        $map_info['imi.isDefault'] = array('EQ', 1);
        $map_info['_logic'] = 'OR';
        $where_info['_complex'] = $map_info;

        /** 4. 查询数据 */
        Session::switchCustomer(0);
        if ($type == 1) {   // 微信
            $table = C('DB_PREFIX') . 'customer_weixin_profile';
            $field = 'imi.id, imi.isDefault, imi.status, imi.type, imi.reviewer, profile.nick_name, profile.head_img, profile.service_type_info, profile.grantStatus';
            if (isset($name) && !empty($name))  $where_info['profile.nick_name']  = array('like', "%$name%");
        } else if ($type == 2) {    // 微博
            $table = C('DB_PREFIX') . 'customer_weibo_profile';
            $field = 'imi.id, imi.isDefault, imi.status, imi.type, imi.reviewer, profile.screen_name as nick_name, profile.profile_image_url as head_img, profile.grantStatus';
            if (isset($name) && !empty($name))  $where_info['profile.screen_name']  = array('like', "%$name%");
        } else if ($type == 3) {    // 头条号
            $table = C('DB_PREFIX') . 'customer_toutiao_profile';
            $field = 'imi.id, imi.isDefault, imi.status, imi.type, imi.reviewer, profile.media_name as nick_name, profile.avatar_url as head_img, profile.grantStatus';
            if (isset($name) && !empty($name))  $where_info['profile.media_name']  = array('like', "%$name%");
        }

        $indMedia_data=[];
        $indMedia_data = $IndMediaInfo_model
            ->alias('imi')
            ->join('left join ' . $table . ' profile ON imi.id = profile.mediaId')
            ->where($where_info)
            ->field($field)
            ->limit($start, $limit)
            ->order('imi.id desc')
            ->select();

        $indMedia_data_count = $IndMediaInfo_model
            ->alias('imi')
            ->join('left join ' . $table . ' profile ON imi.id = profile.mediaId')
            ->where($where_info)
            ->count();
        Session::switchCustomer($customerId);

        /** 4.1 遍历账号, 关联运营人员 */
        $result = [];   // 存放处理后的结果数据
        foreach ($indMedia_data as $indMedia_k => $indMedia_v) {
            /** 4.1.1 关联编辑用户信息, 这地方主要是为了显示管理员 */
            $where_edit = ['mediaId' => $indMedia_v['id']];
            $userIds = $IndMediaEdit_model->where($where_edit)->getField('userId', true);
            $users = [];
            foreach ($userIds as $userId_k => $userId_v) {
                $user = $CustomerUser_model->where(['id' => $userId_v])->field('id, fullName, phone')->find();
                if (!empty($user)) {    // 防止用户被删了的特殊情况
                    array_push($users, $user);
                }
            }

            /** 4.1.2 加入其他固定数据(iconUrl等) */
            if (!isset($indMedia_v['nick_name'])) {
                $indMedia_v['nick_name'] = ($indMedia_v['isDefault'] == 1) ? $defaultMainName : $nick_names[$indMedia_v['type'] - 1];
            }
            // picUrl需要改, 并非一直默认
//            if (!isset($indMedia_v['head_img'])) {
//                $indMedia_v['picurl']  = $picUrls[$indMedia_v['type'] - 1];
//            } else {
//                $indMedia_v['picurl']  = $indMedia_v['head_img'];
//            }
            $indMedia_v['picurl'] = (isset($indMedia_v['head_img'])) ? $indMedia_v['head_img'] : $picUrls[$indMedia_v['type'] - 1];
            $indMedia_v['iconUrl'] = $iconUrls[$indMedia_v['type'] - 1];
            $indMedia_v['status']  = ($indMedia_v['status'] == 1) ? '启用中' : '冻结';
            unset($indMedia_v['type']);

            /** 4.1.3 关联审核人姓名 */
            $indMedia_v['reviewerName'] = '';
            if ($indMedia_v['reviewer'] > 0) {
                $reviewerName = $CustomerUser_model->where(['id' => $indMedia_v['reviewer']])->getField('fullName');
                $indMedia_v['reviewerName'] = $reviewerName;
            }

            /** 4.2 组织该账号的信息 */
            $indMedia = [
                'info'  => $indMedia_v,
                'users' => isset($users) ? $users : []
            ];
            array_push($result, $indMedia);

        }

        /** 5. 返回 */
        if (!empty($result)) {
            $output = [
                'code'  => 0,
                'msg'   => '获取账号列表成功',
                'data'  => [
                    'total' => $indMedia_data_count,
                    'data'  => $result
                ]
            ];
        } else {
            $output = [
                'code'  => 0,
                'msg'   => '暂无账号信息',
                'data'  => []
            ];
        }

        if ($needReturn) {
            return $output;
        }
        Output::instance()->object($output);

    }

    /**
     * 增加一个账号
     *
     * @param int  $type        1-wx/2-wb/3-tth
     */
    public function addIndMedia($type, $gg_cid = 0, $needReturn = FALSE)
    {
        /** 1. 判断是否登录 */
        $this->retVal = Session::init();
        if (!$this->retVal && !$needReturn) {
            Output::instance()->resultCode(code_access_denied);
            exit;
        }

        /** 2. 数据表模型 */
        $userId     = Session::$user['id'];
        $customerId = ($gg_cid == 0) ? Session::$user['customerId'] : $gg_cid;
        Session::switchCustomer(0);
        $IndMediaInfo_model   = M('ind_media_info');
        $IndMediaEdit_model   = M('ind_media_edit');
        $thirdPlatform_model   = M('third_platform');
        $uuid   = Encryption::c_uuid();
        $token  = Encryption::token();
        Session::switchCustomer($customerId);

        /** 3. 筛选条件 */
        /** 3.1 判断登录者身份 */
        /** 这里认为只有运营管理员有添加账号的权限 */
        if (!Session::isBusiness() && ($gg_cid == 0)) {    // 如果不是运营管理员, 则直接返回无权限
            Output::instance()->object([
                'code'  => 1,
                'msg'   => '您无此权限,请联系运营管理员',
                'data'  => []
            ]);
            exit;
        }

        /** 4. 组织数据 */
        $data_media = [
            'cid'       => $customerId,
            'uuid'      => $uuid,
            'token'     => $token,
            'expire'    => date('Y-m-d H:i:s'),
            'type'      => $type,
            'status'    => 1,
            'isDefault' => 0,
            'createTime'=> date('Y-m-d H:i:s'),
            'deleted'   => 0
        ];
        if ($type == 1) {   // 微信数据
            $third_platform_appid = $IndMediaInfo_model->where(['cid' => $customerId, 'isDefault' => 1])->getField('third_platform_appid');
            $data_media['mode']                   = 1;  // 第三方授权方式
            $data_media['third_platform_appid']   = $third_platform_appid;
        } else if ($type == 2) {    // 微博数据
            $third_platform_appid = $thirdPlatform_model->where(['type' => $type])->getField('appid');
            $data_media['mode']                   = 1;  // 第三方授权方式
            $data_media['third_platform_appid']   = $third_platform_appid;
        } else if ($type == 3) {    // 头条号数据
            $third_platform_appid = $thirdPlatform_model->where(['type' => $type])->getField('appid');
            $data_media['mode']                   = 1;  // 第三方授权方式
            $data_media['third_platform_appid']   = $third_platform_appid;
        }

        /** 5. 添加数据 */
        // 添加自媒体账号数据
        $mediaId = $IndMediaInfo_model->add($data_media);

        $IndMediaInfo_sql = $IndMediaInfo_model->getLastSql();
        R('Log/add', array('indmediaManagement', '139', '自媒体管理', op_add, $IndMediaInfo_sql, $this->getLoginName() . '在自媒体管理中新建了一个自媒体账号'));

        /** 6. 结果返回 */
        if (!$mediaId) { // sql有错误, 错误码505
            if ($needReturn) {
                return 0;
            }
            Output::instance()->resultCode(code_sql_error);
        } else {    // 正确码0
            if ($needReturn) {
                return $mediaId;
            }
            $Out = [
                'code'  => 0,
                'msg'   => 'OK',
                'data'  => [
                    'mediaId'   => $mediaId
                ]
            ];
            Output::instance()->object($Out);
        }

    }

    /**
     * 根据mediaId获得指定的账号信息
     *
     * @param $mediaId  自媒体账号id
     */
    public function getIndMediaById($mediaId, $gg_cid = 0, $needReturn = FALSE)
    {
        /**
         * - 先判断是否授权
         *      - 如果没授权, 进行授权操作
         * - 在做持续操作
         * - 需要根据类型, 返回子集菜单
         * - 需要把已经设置的东西组织数据返回
         */

        /** 1. 判断是否登录 */
        $this->retVal = Session::init();
        if (!$this->retVal && !$needReturn) {
            Output::instance()->resultCode(code_access_denied);
            exit;
        }

        /** 2. 数据表模型 */
        $userId     = Session::$user['id'];
        $customerId = ($gg_cid == 0) ? Session::$user['customerId'] : $gg_cid;
        Session::switchCustomer(0);
        $IndMediaInfo_model   = M('ind_media_info');
        $IndMediaEdit_model   = M('ind_media_edit');
        $CWP_model            = M('customer_weixin_profile');
        $CBP_model            = M('customer_weibo_profile');
        $CTP_model            = M('customer_toutiao_profile');
        $GroupUser_model      = M('group_user');
        Session::switchCustomer($customerId);

        /** 3. 筛选条件 */
        $where_info = [];
        $where_info['imi.deleted'] = 0;
        /** 3.1 判断登录者身份 */
        /** 这里假设平台超级管理员是不会到这里的, 到这里, 走的是else */
        if (Session::isBusiness() || ($gg_cid != 0)) {    // 如果是运营管理员, 通过cid和id直接来过滤权限即可
            $where_info['imi.cid']   = array('eq', $customerId);
            $where_info['imi.id']    = array('eq', $mediaId);

        } else {    // 如果是普通运营人员, 则需判断是否拥有这个账号的管理权限
            // 考虑组级的关系: 组长可以看到该组所有组员所运营的账号
            $where_group = [
                'userId'    => $userId,
                'leader'    => 1
            ];
            // 这里的infoId是组id, 这里获取的是以这个用户为组长的组
            $infoIds = $GroupUser_model->where($where_group)->getField('infoId', true);
            if (empty($infoIds)) {  // 如果以他为组长的组为空, 则组员只有自己
                $userIds = [ $userId ];   // 为了与下面统一, 这里也写成一个数组
            } else {
                // 获得已改用户为组长的所有组的所有组员, 这里必然会有用户id重复, 所以在下面做了去重
                $userIds = $GroupUser_model->where(['infoId' => array('in', $infoIds)])->getField('userId', true);
                $userIds = array_keys(array_flip($userIds));    // 数组去重
            }

            // 根据所有组员(编辑人员)的ids, 去查这些人名下的所有账号mediaIds
            $where_edit = ['cid' => $customerId, 'userId' => array('in', $userIds)];
            $mediaIds = $IndMediaEdit_model->where($where_edit)->getField('mediaId', true);
            $mediaIds = isset($mediaIds) ? $mediaIds : [];

            // 判断该用户要查看的账号信息, 是否在这些mediaIds里
            if (in_array($mediaId, $mediaIds)) {    // 如果在权限内, 更加id筛选即可
                $where_info['imi.id']    = array('eq', $mediaId);
            } else {    // 如果不在权限内, 则直接返回无权限
                Output::instance()->object([
                    'code'  => 1,
                    'msg'   => '无该账号管理权限',
                    'data'  => []
                ]);
                exit;
            }
        }

        /** 4. 查询数据 */
        $indMedia_data = $IndMediaInfo_model
            ->alias('imi')
            ->where($where_info)
            ->join('left join wx_customer_user cu ON imi.reviewer = cu.id')
            ->field('imi.*, cu.id as review_id, cu.fullName, cu.phone')
            ->find();

        if ($indMedia_data['type'] == 1) {  // 微信授权信息
            $result = $CWP_model
                ->where(['mediaId' => $indMedia_data['id']])
                ->field('nick_name, head_img, service_type_info, verify_type_info, user_name, principal_name, business_info, alias, qrcode_url, func_info, grantTime, grantStatus, service_open_status')
                ->find();
        } else if ($indMedia_data['type'] == 2) {   // 微博授权信息
            $result = $CBP_model
                ->where(['mediaId' => $indMedia_data['id']])
                ->field('screen_name as nick_name, profile_image_url as head_img, grantStatus')
                ->find();
        } else if ($indMedia_data['type'] == 3) {   // 头条号授权信息
            $result = $CTP_model
                ->where(['mediaId' => $indMedia_data['id']])
                ->field('media_name as nick_name, avatar_url as head_img, grantStatus')
                ->find();
        }

        $indMedia_data = array_merge($indMedia_data, $result);

        // 在这里, 如果检测到该账号尚没有授权给咱们平台, 则返回, 要求其进行授权操作
        if (empty($indMedia_data['grantStatus']) || ($indMedia_data['grantStatus'] == 0)) { // 如果发现没授权, 返回错误码2, 提示授权
            Output::instance()->object([
                'code'  => 2,
                'msg'   => '该公众号尚未授权, 请联系运营管理员进行授权',
                'data'  => []
            ]);
            exit;
        }

        /** 4.1 关联运营人员&类型 */
//        /** 4.1.1 组织这种账号的菜单树 */
//        $tree = $this->getMenuByType($indMedia_data['type']);
//        /** 4.1.2 关联运营用户信息 */
//        $users = $this->getUsers($mediaId, true);
        /** 4.1.3 关联标签信息 */
        $tags = $this->getTags($mediaId, true);
        /** 4.14 关联编辑用户信息 */
        $edits = $this->getEdits($mediaId, true);

        /** 4.2 组织该账号的信息 */
        $indMedia = [
//            'tree'  => $tree,
            'info'  => $indMedia_data,
            'users' => isset($users) ? $users : [],
            'tags'  => isset($tags) ? $tags : [],
            'edits'  => isset($edits) ? $edits : []
        ];

        /** 5. 返回 */
        if (!empty($indMedia_data)) {
            $output = [
                'code'  => 0,
                'msg'   => '获取账号信息成功',
                'data'  => $indMedia
            ];
        } else {
            $output = [
                'code'  => 0,
                'msg'   => '暂无该账号信息',
                'data'  => []
            ];
        }

        if ($needReturn) {
            return $output;
        }
        Output::instance()->object($output);
    }
    /**
     * 获得授权url
     * @param int $mediaId  自媒体Id
     */
    public function get_oauth_url($mediaId)
    {
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $media = M('ind_media_info');
        Session::switchCustomer($customerId);

        $mediaInfo =  $media->field('type,third_platform_appid')->where("id=$mediaId")->find();
        if ($mediaInfo['type'] == 2){
            $oauth_url = WeiboApi::getWeiboAuthorizeUrl($mediaInfo['third_platform_appid'], $mediaId);
        }else if ($mediaInfo['type'] == 3){
            $oauth_url = ToutiaoApi::getToutiaoAuthorizeUrl($mediaInfo['third_platform_appid'], $mediaId);
        }
        $result = array();
        $result['code'] = 0;
        $result['auth_url'] = $oauth_url;
        Output::instance()->object($result);
    }

    /**
     * 设置账号(修改账号)[账号信息/账号类型/账号运营者/编辑者]
     *
     * @param        $mediaId       账号id
     * @param        $status        账号状态: 0-冻结/1-启用中
     * @param int    $needTailPic   是否需要尾图: 0-不需要/1-需要
     * @param string $tailPicUrl    尾图url地址
     * @param int    $ifReview      是否需要审核: 0-不需要/1-需要
     * @param int    $reviewer      审核者id
     * @param string $tags          类别(标签)
     * @param string $edits         被设置的编辑用户
     */
    public function updateIndMedia($mediaId, $status, $needTailPic = 0, $tailPicUrl = '', $ifReview = 0, $reviewer = 0, $tags, $edits = '[]')
    {
        /** 1. 判断是否登录 */
        $this->retVal = Session::init();
        if (!$this->retVal) {
            Output::instance()->resultCode(code_access_denied);
            exit;
        }

        /** 2. 数据表模型 */
        $userId     = Session::$user['id'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $IndMediaInfo_model   = M('ind_media_info');
        $IndMediaEdit_model   = M('ind_media_edit');
        $IndMediaTags_model   = M('ind_media_tags');
        $IndMediaTagRel_model = M('ind_media_tags_rel');
        Session::switchCustomer($customerId);

        /** 3. 修改账号数据 */
        $data_info ['status'] = $status;
        if ($needTailPic) {   // 修改设置需要尾图
            if (!empty($tailPicUrl)) {    // 组织尾图数据修改
                $data_info['needTailPic']   = $needTailPic;
                $data_info['TailPicUrl']    = $tailPicUrl;
            } else {    // 如果设置了需要尾图, 可是没传尾图, 则报错返回
                Output::instance()->object([
                    'code'  => 1,
                    'msg'   => '请上传尾图',
                    'data'  => []
                ]);
                exit;
            }
        }
        if ($ifReview) {    // 修改需要设置尾图
            if ($reviewer != 0) {   // 组织审核人数据
                $data_info['ifReview']  = $ifReview;
                $data_info['reviewer']  = $reviewer;
            } else {
                Output::instance()->object([
                    'code'  => 1,
                    'msg'   => '请设置审核人',
                    'data'  => []
                ]);
                exit;
            }
        } else {
            $data_info['ifReview']  = $ifReview;
            $data_info['reviewer']  = 0;
        }
        $where_info = ['id' => $mediaId];
        $result_info = $IndMediaInfo_model->where($where_info)->save($data_info);

        $IndMediaInfo_sql = $IndMediaInfo_model->getLastSql();
        R('Log/add', array('indmediaManagement', '139', '自媒体管理', op_update, $IndMediaInfo_sql, $this->getLoginName() . '在自媒体管理中修改了账号id为: ' . $mediaId . '的基础配置'));

        /** 4. 修改类别(标签)数据 */
        $where_tagRel = ['mediaId' => $mediaId];
        $tagIds = $IndMediaTagRel_model->where($where_tagRel)->getField('tagId', true);
        $tagIds = (!empty($tagIds)) ? $tagIds : [];
        $tags = json_decode($tags);     // 解json数据
        /** 4.1 数组差集, 获得此次新增/删除的标签  */
        $arr_tags_add = array_values(array_diff($tags, $tagIds));
        $arr_tags_del = array_values(array_diff($tagIds, $tags));
        /** 4.2 新增标签 */
        if (!empty($arr_tags_add)) {
            $data_tagRel_add = [];
            foreach ($arr_tags_add as $add_k => $add_v) {
                $data_tagRel = [
                    'mediaId'   => $mediaId,
                    'tagId'     => $add_v
                ];
                array_push($data_tagRel_add, $data_tagRel);
            }
            $result_tagRel_add = $IndMediaTagRel_model->addAll($data_tagRel_add);

            $IndMediaTagRel_sql = $IndMediaTagRel_model->getLastSql();
            R('Log/add', array('indmediaManagement', '139', '自媒体管理', op_update, $IndMediaTagRel_sql, $this->getLoginName() . '在自媒体管理中修改了账号id为: ' . $mediaId . '的标签, 做了一些添加'));
        }
        /** 4.3 删除标签 */
        if (!empty($arr_tags_del)) {
            $where_tagRel_del = [
                'mediaId'   => $mediaId,
                'tagId'     => array('in', $arr_tags_del)
            ];
            $result_tagRel_del = $IndMediaTagRel_model->where($where_tagRel_del)->delete();
            $IndMediaTagRel_sql = $IndMediaTagRel_model->getLastSql();
            R('Log/add', array('indmediaManagement', '139', '自媒体管理', op_delete, $IndMediaTagRel_sql, $this->getLoginName() . '在自媒体管理中修改了账号id为: ' . $mediaId . '的标签, 做了一些删除'));
        }

        /** 6. 修改编辑用户数据关联 */
        $where_edit = ['mediaId' => $mediaId];
        $editIds = $IndMediaEdit_model->where($where_edit)->getField('userId', true);
        $editIds = (!empty($editIds)) ? $editIds : [];
        $edits = json_decode($edits);
        /** 6.1 数组差集 */
        $arr_edits_add = array_values(array_diff($edits, $editIds));
        $arr_edits_del = array_values(array_diff($editIds, $edits));
        /** 6.2 新增编辑人员 */
        if (!empty($arr_edits_add)) {
            $data_edit_add = [];
            foreach ($arr_edits_add as $add_k => $add_v) {
                $data_edit = [
                    'mediaId'   => $mediaId,
                    'userId'     => $add_v
                ];
                array_push($data_edit_add, $data_edit);
            }
            $result_edit_add = $IndMediaEdit_model->addAll($data_edit_add);

            $IndMediaEdit_sql = $IndMediaEdit_model->getLastSql();
            R('Log/add', array('indmediaManagement', '139', '自媒体管理', op_update, $IndMediaEdit_sql, $this->getLoginName() . '在自媒体管理中修改了账号id为: ' . $mediaId . '的运营编辑, 做了一些添加'));
        }
        /** 6.1 删除编辑人员 */
        if (!empty($arr_edits_del)) {
            $where_edit_del = [
                'mediaId'   => $mediaId,
                'userId'    => array('in', $arr_edits_del)
            ];
            $result_edit_del = $IndMediaEdit_model->where($where_edit_del)->delete();

            $IndMediaEdit_sql = $IndMediaEdit_model->getLastSql();
            R('Log/add', array('indmediaManagement', '139', '自媒体管理', op_update, $IndMediaEdit_sql, $this->getLoginName() . '在自媒体管理中修改了账号id为: ' . $mediaId . '的运营编辑, 做了一些添加'));
        }



        /** 7. 返回 */
        if ((!($result_info == 0 || $result_info == 1))
            || (isset($result_tagRel_add) && !$result_tagRel_add)
            || (isset($result_tagRel_del) && !$result_tagRel_del)
            || (isset($result_edit_add) && !$result_edit_add)
            || (isset($result_edit_del) && !$result_edit_del))
        {
            Output::instance()->resultCode(code_sql_error);
        } else {
            Output::instance()->resultCode();
        }
    }

    /**
     * 删除账号
     *
     * @param $mediaId  自媒体账号id
     */
    public function deleteIndMedia($mediaId)
    {
        /** 1. 判断是否登录 */
        $this->retVal = Session::init();
        if (!$this->retVal) {
            Output::instance()->resultCode(code_access_denied);
            exit;
        }

        /** 2. 数据表模型 */
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $IndMediaInfo_model   = M('ind_media_info');
        Session::switchCustomer($customerId);

        /** 3. 筛选条件 */
        /** 3.1 判断登录者身份 */
        /** 这里认为只有运营管理员有删除账号的权限 */
        if (!Session::isBusiness()) {    // 如果不是运营管理员, 则直接返回无权限
            Output::instance()->object([
                'code'  => 1,
                'msg'   => '您无此权限,请联系运营管理员',
                'data'  => []
            ]);
            exit;
        }

        $where = ['id' => $mediaId];
        $isDefault = $IndMediaInfo_model->where($where)->getField('isDefault');
        if ($isDefault == 1) {  // 是默认账号, 不允许删除
            Output::instance()->object([
                'code'  => 1,
                'msg'   => '此账号是系统账号, 不可删除',
                'data'  => []
            ]);
            return;
        }
        $data = ['deleted' => 1];

        $result = $IndMediaInfo_model->where($where)->save($data);

        $IndMediaInfo_sql = $IndMediaInfo_model->getLastSql();
        R('Log/add', array('indmediaManagement', '139', '自媒体管理', op_delete, $IndMediaInfo_sql, $this->getLoginName() . '在自媒体管理中删除了账号id为: ' . $mediaId . '的自媒体'));

        if (!($result == 0 || $result == 1)) {
            Output::instance()->resultCode(code_sql_error);
        } else {
            Output::instance()->resultCode();
        }
    }

    /**
     * 添加标签
     *
     * @param $tagName  标签名
     */
    public function addTag($tagName)
    {
        /** 1. 判断是否登录 */
        $this->retVal = Session::init();
        if (!$this->retVal) {
            Output::instance()->resultCode(code_access_denied);
            exit;
        }

        /** 2. 数据表模型 */
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $IndMediaTags_model   = M('ind_media_tags');
        Session::switchCustomer($customerId);

        /** 3. 添加标签 */
        $data_tags = ['cid' => $customerId, 'tagName' => $tagName];
        $tagId = $IndMediaTags_model->add($data_tags);

        $IndMediaTags_sql = $IndMediaTags_model->getLastSql();
        R('Log/add', array('indmediaManagement', '139', '自媒体管理', op_add, $IndMediaTags_sql, $this->getLoginName() . '在自媒体管理中新增了一个标签, 名为: ' . $tagName));

        /** 4. 返回 */
        if ($tagId) {
            Output::instance()->object([
                'code'  => 0,
                'msg'   => '标签添加成功',
                'data'  => ['tagId' => $tagId]
            ]);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    /**
     * 删除标签
     * @param $Id 标签id
     */
    public function deltag($Id)
    {
        /** 1. 判断是否登录 */
        $this->retVal = Session::init();
        if (!$this->retVal) {
            Output::instance()->resultCode(code_access_denied);
            exit;
        }

        /** 2. 数据表模型 */
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $IndMediaTags_model = M('ind_media_tags');
        Session::switchCustomer($customerId);

        $data['deleted'] = 1;
        $datas['id'] = $Id;
        $res = $IndMediaTags_model->where($datas)->save($data);

        $IndMediaTags_sql = $IndMediaTags_model->getLastSql();
        R('Log/add', array('indmediaManagement', '139', '自媒体管理', op_delete, $IndMediaTags_sql, $this->getLoginName() . '在自媒体管理中删除一个标签, 标签id为: ' . $Id));

        if (is_numeric($res)) {
            Output::instance()->object([
                'code' => 0,
                'msg' => '删除标签成功',
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '删除标签失败',
            ]);
        }

    }

    /**
     * 获得某个账号的标签设置情况
     *
     * @param      $mediaId     账号id
     * @param bool $needReturn  是否直接返回数组而不向页面输出(内部接口调用)
     * @return mixed
     */
    public function getTags($mediaId, $needReturn = false)
    {
        /** 1. 判断是否登录 */
        $this->retVal = Session::init();
        if (!$needReturn && !$this->retVal) {
            Output::instance()->resultCode(code_access_denied);
            exit;
        }

        /** 2. 数据表模型 */
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $IndMediaTags_model   = M('ind_media_tags');
        $IndMediaTagRel_model = M('ind_media_tags_rel');
        Session::switchCustomer($customerId);

        /** 3. 组织查询标签数据 */
        $data['cid']=$customerId;
        $data['deleted']=0;
        $where_tags = ['mediaId' => $mediaId];
        $tagIds = $IndMediaTagRel_model->where($where_tags)->getField('tagId', true);
        $tags   = $IndMediaTags_model->where($data)->field('id, tagName, deleted')->order('id', 'asc', 'deleted')->select();
        foreach ($tags as $tag_k => $tag_v) {
            // 如果这个id在这个媒体设置的类别的tagIds数组里, 则这个标签选中, 否则没选中
            $tags[$tag_k]['isSelect'] = in_array($tag_v['id'], $tagIds) ? 1 : 0;
        }

        /** 4. 返回 */
        if ($needReturn) {  // 内部调用, 直接返回结果数组
            return $tags;
        }
        if (!empty($tags)) {
            Output::instance()->object([
                'code'  => 0,
                'msg'   => 'API调用成功',
                'data'  => $tags
            ]);
        } else {
            Output::instance()->object([
                'code'  => 0,
                'msg'   => '暂无标签数据',
                'data'  => []
            ]);
        }
    }

    /**
     * 获得某个自媒体账号的编辑用户列表
     *
     * @param      $mediaId     自媒体账号id
     * @param bool $needReturn  是否直接返回数组而不向页面输出(内部接口调用)
     * @return mixed
     */
    public function getEdits($mediaId, $needReturn = false)
    {
        /** 1. 判断是否登录 */
        $this->retVal = Session::init();
        if (!$needReturn && !$this->retVal) {
            Output::instance()->resultCode(code_access_denied);
            exit;
        }

        /** 2. 数据表模型 */
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $IndMediaEdit_model   = M('ind_media_edit');
        $CustomerUser_model   = M('customer_user');
        Session::switchCustomer($customerId);

        /** 3. 组织查询编辑用户数据 */
        $where_edit = ['mediaId' => $mediaId];
        $editIds = $IndMediaEdit_model->where($where_edit)->getField('userId', true);
        $edits = [];
        foreach ($editIds as $editId_k => $editId_v) {
            $edit = $CustomerUser_model->where(['id' => $editId_v, 'status' => 'open'])->field('id, fullName, phone')->order('id', 'desc')->find();
            if ($edit) {
                array_push($edits, $edit);
            }
        }

        /** 4. 返回 */
        if ($needReturn) {  // 内部调用, 直接返回结果数组
            return $edits;
        }
        if (!empty($edits)) {
            Output::instance()->object([
                'code'  => 0,
                'msg'   => 'API调用成功',
                'data'  => $edits
            ]);
        } else {
            Output::instance()->object([
                'code'  => 0,
                'msg'   => '暂无编辑用户数据',
                'data'  => []
            ]);
        }
    }

    /**
     * 获得运营用户列表
     * 在点击设置运营人员时, 获得所有当前登录者下面的运营人员, 以便添加删除
     *
     * @param      $mediaId 自媒体id - 用于查询当前自媒体下已经拥有的运营人员
     * @param null $name    运营人员姓名搜索
     * @param int  $start
     * @param int  $limit
     * @param int  $isAddReviewer   是否是添加审核人, 1-是/0-不是
     */
    public function getUserList($mediaId, $name = null, $start = 0, $limit = 10, $isAddReviewer = 0)
    {
        /** 1. 判断是否登录 */
        $this->retVal = Session::init();
        if (!$this->retVal) {
            Output::instance()->resultCode(code_access_denied);
            exit;
        }

        /** 2. 数据表模型 */
        $userId     = Session::$user['id'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $IndMediaEdit_model   = M('ind_media_edit');
        $CustomerUser_model   = M('customer_user');
        $GroupUser_model      = M('group_user');
        $role_model           = M('role');
        $CustomerUserDetail_model = M('customer_user_detail');
        Session::switchCustomer($customerId);

        /** 3. 筛选条件 */
        $where_user = [];
        $where_customerUser = [];
        $where_customerUser['agent'] = 'insideUser';
        $where_customerUser['cu.status'] = 'open';
        if (!empty($name)) $where_customerUser['cu.fullName'] = array('like', "%$name%");

        /** 3.1 判断登录者身份 */
        /** 这里假设平台超级管理员是不会到这里的, 到这里, 走的是else */
        if ( Session::isBusiness() ) {    // 如果是运营管理员, 则直接查询cid
            $where_customerUser['cu.customerId']   = array('eq', $customerId);
        } else {    // 如果是普通运营人员, 则通过ind_media_edit过滤查询这个用户管理的这些账号

            // 考虑组级的关系: 组长可以看到该组所有组员所运营的账号
            $where_group = [
                'userId'    => $userId,
                'leader'    => 1
            ];
            // 这里的infoId是组id, 这里获取的是以这个用户为组长的组
            $infoIds = $GroupUser_model->where($where_group)->getField('infoId', true);
            if (empty($infoIds)) {  // 如果以他为组长的组为空, 则组员只有自己
                $userIds = [ $userId ];   // 为了与下面统一, 这里也写成一个数组

            } else {
                // 获得以该用户为组长的所有组的所有组员, 这里必然会有用户id重复, 所以在下面做了去重
                $userIds = $GroupUser_model->where(['infoId' => array('in', $infoIds)])->getField('userId', true);
                $userIds = array_keys(array_flip($userIds));    // 数组去重
            }

            $where_customerUser['cu.id']   = array('in', $userIds);
        }

        // 3.1.2 后去客户列表, 将客户排除在外
        $clientIds = $CustomerUserDetail_model->where(['deleteTime' => ['EXP', 'is null']])->distinct(true)->field('clientId')->select();
        $clientIds = array_column($clientIds, clientId);
        if (!empty($clientIds)) {
            $where_customerUser['cu.id'] = ['NOT IN', $clientIds];
        }

        /** 3.2 根据上面查询条件, 查询所有符合条件的运营用户 */
        if (!$isAddReviewer) {
            $roleId = $role_model->where(['cid' => $customerId, 'englishRole' => role_edit])->getField('id');
            $where_customerUser['cur.roleId'] = $roleId;  // 编辑角色

            $users = $CustomerUser_model
                ->alias('cu')
                ->join('wx_customer_user_role cur ON cur.userId = cu.id')
                ->where($where_customerUser)
                ->field('cu.id, cu.fullName, cu.phone')
                ->order('id', 'desc')
                ->limit($start, $limit)
                ->select();
            $users_count = $CustomerUser_model
                ->alias('cu')
                ->join('wx_customer_user_role cur ON cur.userId = cu.id')
                ->where($where_customerUser)
                ->count();
        } else {
            $users = $CustomerUser_model
                ->alias('cu')
                ->where($where_customerUser)
                ->field('cu.id, cu.fullName, cu.phone')
                ->order('id', 'desc')
                ->limit($start, $limit)
                ->select();
            $users_count = $CustomerUser_model
                ->alias('cu')
                ->where($where_customerUser)
                ->count();
        }

        /** 3.3 查询该自媒体账号已设置的编辑用户 */
        $where_edit['mediaId'] = $mediaId;
        $media_users = $IndMediaEdit_model->where($where_edit)->getField('userId', true);

        /** 3.4 遍历所有用户, 组织选中情况 */
        foreach ($users as $user_k => $user_v) {
            $users[$user_k]['isSelect'] = (in_array($user_v['id'], $media_users)) ? 1 : 0;
        }

        /** 4. 返回 */
        if (!empty($users)) {
            Output::instance()->object([
                'code'  => 0,
                'msg'   => 'API调用成功',
                'data'  => [
                    'total' => $users_count,
                    'data'  => $users
                ]
            ]);
        } else {
            Output::instance()->object([
                'code'  => 0,
                'msg'   => '暂无运营用户数据',
                'data'  => []
            ]);
        }
    }

    /**
     * 获得账号的菜单
     *
     * @param $mediaId  获得菜单信息需要自媒体id, 所以这里url需要拼上
     */
    public function getMenuByType($mediaId)
    {
        $type = M()->table('wx_ind_media_info')->where(['id' => $mediaId])->getField('type');
        // 类别数组, 目前就wx-微信/wb-微博/tth-头条号三种
        $keys = ['wx', 'wb', 'tth'];
        $key  = $keys[$type - 1];   // 根据参数$type知道需要获得那种类型的菜单

        // 菜单配置数组
        $data = [
            'wx'    => [
                'group'     => '微信账号设置',
                'children'  => [
                    [
                        'name'  => '基础设置',
                        'url'   => '#/joymap/selfmedia/detail/' . $mediaId . '/baseConfig',
                    ],
                    [
                        'name'  => '授权',
                        'url'   => '#/joymap/selfmedia/detail/' . $mediaId . '/auth/normal',
                    ],
                    [
                        'name'  => '自定义菜单',
                        'url'   => '#/joymap/selfmedia/detail/' . $mediaId . '/customMenu',
                    ],
                    [
                        'name'  => '自动回复',
                        'url'   => '#/joymap/selfmedia/detail/' . $mediaId . '/autoReply',
                    ],
                    [
                        'name'  => '粉丝管理',
                        'url'   => '#/joymap/selfmedia/detail/' . $mediaId . '/fansManager',
                    ],
                    [
                        'name'  => '评论管理',
                        'url'   => '#/joymap/selfmedia/detail/' . $mediaId . '/newsComment',
                    ]
                ]
            ],
            'wb'    => [
                'group'     => '微博账号设置',
                'children'  => [
                    [
                        'name'  => '基础设置',
                        'url'   => '#/joymap/selfmedia/detail/' . $mediaId . '/baseConfig',
                    ],
                    [
                        'name'  => '授权',
                        'url'   => '#/joymap/selfmedia/detail/' . $mediaId . '/auth/normal',
                    ],
                    [
                        'name'  => '粉丝管理',
                        'url'   => '#/joymap/selfmedia/detail/' . $mediaId . '/fansManager',
                    ]
                ]
            ],
            'tth'    => [
                'group'     => '微博账号设置',
                'children'  => [
                    [
                        'name'  => '基础设置',
                        'url'   => '#/joymap/selfmedia/detail/' . $mediaId . '/baseConfig',
                    ],
                    [
                        'name'  => '授权',
                        'url'   => '#/joymap/selfmedia/detail/' . $mediaId . '/auth/normal',
                    ]
                ]
            ]
        ];

        $index = 1;
        $arr_child = [];
        foreach ($data[$key]['children'] as $child_k => $child_v) {
            // 这个菜单是_胡英俊_给出的菜单树demo结构
            $m = [
                'id'        => $index,
                'name'      => $child_v['name'],
                'level'     => 1,
                'parent'    => 0,
                'path'      => "$index",
                'icon'      => '',
                'url'       => $child_v['url'],
                'isMenu'    => true,
                'children'  => []
            ];
            array_push($arr_child, $m);
            $index++;
        }

        $menu = [
            'id'        => 0,
            'group'     => $data[$key]['group'],
            'children'  => $arr_child
        ];


        Output::instance()->object(['data' => [$menu]]);
    }

    /**
     * 生成获取微信历史素材定时任务
     * @param $mediaId /自媒体id
     */

    public function addGetWxNews($mediaId)
    {
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $task_tab = M('task_queue');
        Session::switchCustomer($cid);
        //是否存在此任务
        $where = [];
        $where['cid'] = $cid;
        $where['name'] = 'getWxNews';
        $where['module'] = 'indmediaManagement';
        $where['param'] = $mediaId;
        $where['status'] = [['eq',1],['eq',2], 'or'];
        $taskRet = $task_tab->where($where)->find();
        if($taskRet !== null){
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'此任务已创建,不能重复创建',
                'results'=>[]
            ]);
            return;
        }
        $bool = R('TaskQueue/addTaskQueue', [$name='getWxNews', $module='indmediaManagement',
            $interfaceName='IndMediaAction/getWxNews',$param=$mediaId,
            $execute_plan_time=date('Y-m-d H:i:s'), $flag=true,$isCycleExecute=0, $cycleTime=0, $cId = $cid]);
        if(!$bool){
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'任务创建失败',
                'results'=>[]
            ]);
            return;
        }
        Output::instance()->object([
            'code'=>0,
            'msg'=>'任务创建成功',
            'results'=>[]
        ]);
    }

    /**
     * 获取历史素材定时任务结果
     * @param int $mediaId /自媒体id
     */
    public function getTaskInfo($mediaId)
    {
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $task_tab = M('task_queue');
        Session::switchCustomer($cid);
        $where = [];
        $where['cid'] = $cid;
        $where['name'] = 'getWxNews';
        $where['module'] = 'indmediaManagement';
        $where['param'] = $mediaId;
        $taskInfo = $task_tab->where($where)->order('id desc')->find();
        if($taskInfo == null){
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'暂无获取素材任务',
                'results'=>[]
            ]);
            return;
        }
        $newsCount = 0;
        if($taskInfo['status'] == 1){
            $taskInfo['status'] = '待执行';
        }else if($taskInfo['status'] == 2){
            $taskInfo['status'] = '执行中';
        }else{
            $taskInfo['status'] = '执行完成';
            $retArr = explode('|', $taskInfo['result']);
            $newsCount = explode(':', $retArr[0]);
        }
        $taskInfo['newsCount'] = $newsCount;
        Output::instance()->object([
            'code'=>0,
            'msg'=>'ok',
            'results'=>$taskInfo
        ]);
    }

    /**
     * 获取微信历史素材
     * @param $taskInfo /任务信息
     * @return string
     * @throws Exception
     */
    public function getWxNews($taskInfo)
    {
        Session::init();
        $mediaId = $taskInfo['param'];
        $accessToken = WeixinApi::getAccessToken(true,null,null,$mediaId);
        if(!$accessToken){
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'获取accessToken失败'
            ]);
            return;
        }
        //设置执行时间无限
        if (ini_get('max_execution_time')) {
            ini_set('max_execution_time', '0');
        }
        //测试获取公众号素材总数
        $total = self::getWxNewsNum($accessToken);
        $count = 10; //每次拉取十条
        $num  = $total<=0 ? 0 : ceil($total/$count);
        $retInfo = '';
        $getNewsCount = 0;
        for($i=0;$i<$num;$i++){
            $dataList = [];
            //分页获取图文素材
            $url= "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=$accessToken";
            $param = json_encode([
                "type"=>'news',
                "offset"=>$i*$count,        //每次请求偏移量
                "count"=>$count             //每次请求数量
            ]);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $result = json_decode(curl_exec($ch),true);
            if(curl_getinfo($ch,CURLINFO_HTTP_CODE) !==200){
                $retInfo .= curl_error($ch).'|';
            }
            curl_close($ch);
            $material_table = M('material');
            //处理获取的数组
            if($result['item']){
                foreach($result['item'] as $val){
                    $dataArr = [];
                    $title = '';
                    $xml = '';

                    //如果单图文,直接判断表中是否存在
                    if(count($val['content']['news_item']) == 1){
                        $serRet = $material_table->where(['module'=>'material','name'=>$val['content']['news_item'][0]['title'],'mediaId'=>$mediaId, 'type'=>'news'])->find();
                        if($serRet){
                            continue;
                        }
                    }

                    if($val['content']['news_item']){
                        $newResult = self::assembleXml($val['content']['news_item']);
                        $title = trim($newResult['title'],',');
                        $serRet = $material_table->where(['module'=>'material','name'=>$title,'mediaId'=>$mediaId, 'type'=>'news'])->find();
                        if($serRet){
                            //表中存在,直接跳过
                            continue;
                        }
                        $xml = $newResult['xml'];
                    }
                    $dataArr['name'] = $title;  //标题拼接
                    //$dataArr['media_id'] = $val['media_id'];  //media_id暂不存,避免永久素材限制
                    $dataArr['module'] = 'material';
                    $dataArr['xml'] = $xml;
                    $dataArr['updateTime'] = date('Y-m-d H:i:s', $val['update_time']);
                    $dataArr['type'] = 'news';
                    $dataArr['public'] = 0;
                    $dataArr['backups'] = 0;
                    $dataArr['mediaId'] = $mediaId;
                    $ret = $material_table->add($dataArr);
                    if(!$ret){
                        $retInfo .= $ret.'|';
                    }
                    $getNewsCount++;
                    //$dataList[] = $dataArr;
                }

                /*if($dataList){
                    $wxSaveSql = 'insert into wx_3_material (`name`,`module`,`xml`,`updateTime`,`type`,`public`) VALUES ';
                    foreach ($dataList as $v) {
                        $wxSaveSql .= "('" . $v['name'] . "','" . $v['module'] . "','" . $v['content'] . "','" . $v['update_time'] . "','news', 0),";
                    }
                    $wxSaveSql = trim($wxSaveSql, ',') . ';';
                    $ret = M()->execute($wxSaveSql);
                    if(!$ret){
                        echo 'jie--------111';
                        var_dump(M()->getLastSql());
                    }
                }*/
            }
        }
        if(strlen($retInfo)>300){
            $retInfo = substr($retInfo,0,300);
        }else if(strlen($retInfo)<1){
            $retInfo = 'ok';
        }
        $retInfo = 'newsCount:'.$getNewsCount.'|'.$retInfo;
        $retSql = "UPDATE `wx_task_queue` SET  `result`='".$retInfo."',`updateTime`='".date('Y-m-d H:i:s')."' WHERE (`id`=".$taskInfo['id'].")";
        M()->execute($retSql);
        return true;
    }

    /**
     * 组装xml
     * @param array $item /一条图文的内容
     * @return string
     */
    public function assembleXml($item)
    {
        $downLoadDir = TEMP_FILE;//临时目录
        $title = '';
        $xml = '<xml><Articles>';
        foreach ($item as $val) {
            $title .= $val['title'].',';
            //将内容中的图片URL处理成oss上面的图片
            $content = $val['content'];
            if($val['content']){
                $content = self::replaceImg($val['content'], $downLoadDir);
            }
            $thumb_url = $val['thumb_url'];
            if($val['thumb_url']){
                $thumb_url = self::replaceImg($val['thumb_url'], $downLoadDir, 1);
            }
            $xml .= '<item>
<title><![CDATA[' . $val['title'] . ']]></title>
<content><![CDATA[<p>' .$content . '<img class="loadingclass" id="loading_j6ublzmf" src="./thirdsources/editor_135.assets/themes/default/images/spacer.gif"/></p>]]></content>
<picUrl><![CDATA[' . $thumb_url . ']]></picUrl>
<author><![CDATA[' . $val['author'] . ']]></author>
<description><![CDATA[' . $val['digest'] . ']]></description>
<content_source_url><![CDATA[' . $val['url'] . ']]></content_source_url>
</item>';
        }
        $xml .= '</Articles></xml>';
        return [
            'title' => $title,
            'xml' => $xml
        ];
    }

    /**
     * 将图片上传到oss,替换文章中的图片路径
     * @param array $item /一条内容
     * @param string $downLoadDir 临时保存文件夹
     * @param int $type /判断是内容还是封面图片
     * @return string
     */
    public function replaceImg($item, $downLoadDir, $type=0){
        $cid = session('customerId')?session('customerId'):3;
        //保存路径
        if(!is_dir($downLoadDir)){
            self::createDir($downLoadDir);
        }

        if($type == 1){
            //处理封面图片
            $img=file_get_contents($item);
            if($img == false){
                return $item;
            }

            $fileimgname = time()."-".rand(1000,9999).'.jpeg';
            $filecachs=$downLoadDir."/".$fileimgname;
            //先保存在本地
            $int = file_put_contents($filecachs, $img);
            if(!$int){
                return $item;
            }
            //上传oss,获取链接
            $upRet = R('Upload/uploadLocalFileToOss', [$fileimgname, $filecachs]);
            $fileInfo = $upRet->path;
            if(!$fileInfo){
                return $item;
            }
            return $fileInfo;
        }

        //处理图文中的图片,匹配图片的src
        $item = str_replace('data-src', 'src', $item);
        preg_match_all('#<img.*?src="([^"]*)".*?>#i', $item, $match);
        foreach($match[1] as $imgUrl){
            $img=file_get_contents($imgUrl);
            if($img == false){
                continue;
            }
            if(!empty($img)) {
                //保存图片到服务器
                $fileimgname = time()."-".rand(1000,9999).'.jpeg';
                $filecachs=$downLoadDir."/".$fileimgname;
                //先保存在本地
                $int = file_put_contents( $filecachs, $img);
                if(!$int){
                    continue;
                }
                //上传oss,获取链接
                $upRet = R('Upload/uploadLocalFileToOss', [$fileimgname, $filecachs]);
                $fileInfo = $upRet->path;
                if(!$fileInfo){
                    continue;
                }
                //替换文章中的路径
                $item=str_replace($imgUrl,$fileInfo,$item);
            }
        }
        return $item;
    }

    /**
     * 获取图文素材的数量
     * @param $accessToken
     * @return int
     */
    public function getWxNewsNum($accessToken){
        $countUrl= "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=$accessToken";
        $ch = curl_init($countUrl) ;
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
        $res= json_decode(curl_exec($ch), true);
        curl_close($ch);
        return $res['news_count'];
    }

    /**
     * 创建对应的文件夹
     * @param $save_dir /文件夹名称
     * @throws Exception
     */
    public function createDir($save_dir)
    {
        //$save_dir = APP_PATH.'../updateDoc/datas';
        if (trim($save_dir) == '') {
            //保存的文件夹
            $save_dir = './';
        }
        if (0 !== strrpos($save_dir, '/')) {
            $save_dir .= '/';
        }
        //创建保存目录
        if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
            //创建文件夹失败
            throw new Exception('创建文件夹失败');
        }
    }

    /**
     * 获取登录者姓名
     */
    private function getLoginName()
    {
        $cuid = Session::$user['cuid'];
        $customerId = Session::$user['custoerId'];

        Session::switchCustomer(0);
        $Model_CustomerUser = M('customer_user');
        Session::switchCustomer($customerId);

        $loginName = $Model_CustomerUser->where(['id' => $cuid, 'deleted' => 0])->getField('loginName');

        return $loginName;
    }

    /**
     * 获得审核人列表
     *
     * @param int $type 1-wx/2-wb/3-tth
     */
    public function getReviewers($type = 1)
    {
        /** 1. 判断是否登录 */
        $this->retVal = Session::init();
        if (!$this->retVal) {
            Output::instance()->resultCode(code_access_denied);
            exit;
        }

        /** 2. 数据表模型 */
        $userId     = Session::$user['id'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $IndMediaInfo_model   = M('ind_media_info');
        Session::switchCustomer($customerId);

        /** 3. 获得审核人id数组 */
        $Where_reviewers = [
            'imi.cid' => $customerId,
            'imi.type' => $type,
            'imi.deleted' => 0,
            'imi.ifReview' => 1,
            'imi.reviewer' => ['GT', 0]
        ];
        $reviewers = $IndMediaInfo_model
            ->alias('imi')
            ->join('wx_customer_user cu ON cu.id = imi.reviewer')
            ->where($Where_reviewers)
            ->group('imi.reviewer')
            ->field('cu.id, cu.fullName')
            ->select();

        /** 4. 获得自媒体信息 */
        $Where_imi = [
            'imi.cid' => $customerId,
            'imi.type' => $type,
            'imi.deleted' => 0,
            'imi.reviewer' => ['IN', array_column($reviewers, 'id')]
        ];
        if ($type == 2) {
            $mediaInfos = $IndMediaInfo_model
                ->alias('imi')
                ->join('wx_customer_weibo_profile cwp ON cwp.mediaId = imi.id')
                ->where($Where_imi)
                ->field('imi.id, imi.reviewer, cwp.screen_name as nick_name, cwp.profile_image_url as head_img')
                ->select();
        } else {
            $mediaInfos = $IndMediaInfo_model
                ->alias('imi')
                ->join('wx_customer_weixin_profile cwp ON cwp.mediaId = imi.id')
                ->where($Where_imi)
                ->field('imi.id, imi.reviewer, cwp.nick_name, cwp.head_img')
                ->select();
        }

        /** 5. 处理数据 */
        foreach ($reviewers as $k_reviewer => $v_reviewer) {
            $reviewers[$k_reviewer]['medias'] = [];
            foreach ($mediaInfos as $k_mediaInfo => $v_mediaInfo) {
                if ($v_mediaInfo['reviewer'] == $v_reviewer['id']) {
                    array_push($reviewers[$k_reviewer]['medias'], $v_mediaInfo);
                }
            }
        }

        /** 6. 返回 */
        $Out = [
            'code' => 0,
            'msg' => '查询审核人及其自媒体信息成功',
            'data' => [
                'reviewers' => $reviewers
            ]
        ];
        Output::instance()->object($Out);
    }
}
